<template>
  <div>
    <!-- 对话框 -->
    <el-dialog
      title="填写对应字段在JSON数据中的KEY名称"
      :visible.sync="visible"
      :close-on-click-modal="false"
      :show-close="false"
      center
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="110px">
        <!-- JSON数据 -->
        <!--        <el-form-item label="JSON数据" prop="jsonData">
                  <el-input
                    type="textarea"
                    v-model="form.jsonData"
                    placeholder="请输入JSON数据"
                  ></el-input>
                </el-form-item>-->
        <!-- JSON 数据 -->
        <el-form-item label="JSON数据" prop="jsonData">
          <div class="json-upload-input">
            <!-- 文件上传/拖拽 -->
            <el-upload
              class="upload-demo"
              drag
              accept=".json"
              :show-file-list="false"
              :before-upload="handleFile"
            >
              <i class="el-icon-upload"/>
              <div class="el-upload__text">
                将JSON文件拖到此处或点击上传（或手动输入JSON）
              </div>
            </el-upload>
            <el-input
              v-model="form.jsonData"
              type="textarea"
              placeholder="请输入JSON数据或通过文件导入"
              rows="6"
            />
          </div>
        </el-form-item>

        <!-- 单词列表的键（改成下拉） -->
        <el-form-item label="单词列表的键" prop="listKey">
          <el-select
            v-model="form.listKey"
            placeholder="请选择单词列表的键"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in jsonKeys"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 单词全拼（改成下拉） -->
        <el-form-item label="单词全拼" prop="fullSpell">
          <el-select
            v-model="form.fullSpell"
            placeholder="请选择单词全拼 KEY"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in jsonKeys"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 排序（不可编辑） -->
        <el-form-item label="排序">
          <el-input :disabled="true" placeholder="系统自动排序"></el-input>
        </el-form-item>

        <!-- 词根汇总（改成下拉） -->
        <el-form-item label="词根汇总">
          <el-select
            v-model="form.rootSummary"
            placeholder="请选择词根汇总 KEY"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in jsonKeys"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 难度等级（保持下拉，和原来一致） -->
        <el-form-item label="难度等级" prop="difficultyLevel">
          <el-select
            v-model="form.difficultyLevel"
            placeholder="难度等级 KEY"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in levelOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 频次（改成下拉） -->
        <el-form-item label="频次">
          <el-select
            v-model="form.occurrence"
            placeholder="请选择频次 KEY"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in jsonKeys"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 文件导入后选择键的弹框 -->
    <el-dialog
      title="选择 JSON 键"
      :visible.sync="fileDialogVisible"
      width="60%"
      :show-close="false"
      center
    >
      <div style="display:flex; height:400px;">
        <!-- 左侧键树 -->
        <el-scrollbar style="width:40%; border-right:1px solid #eee; padding:10px;">
          <el-tree
            :data="treeData"
            :props="treeProps"
            node-key="key"
            highlight-current
            @node-click="selectKey"
          />
        </el-scrollbar>

        <!-- 右侧值展示 -->
        <el-scrollbar style="flex:1; padding:10px;">
          <pre>{{ selectedValue }}</pre>
        </el-scrollbar>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="fileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmKey">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { analyzeWordFromJson } from '@/api/wordSystemWordLibrary'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        jsonData: '',
        listKey: 'data',
        fullSpell: 'word',
        rootSummary: '',
        difficultyLevel: '',
        occurrence: ''
      },
      rules: {
        jsonData: [{ required: true, message: '请输入JSON数据', trigger: 'blur' }],
        listKey: [{ required: true, message: '请选择单词集合的键', trigger: 'change' }],
        fullSpell: [{ required: true, message: '请选择单词全拼 KEY', trigger: 'change' }],
        difficultyLevel: [{ required: true, message: '请选择难度等级', trigger: 'change' }]
      },
      levelOptions: [],
      jsonKeys: [], // JSON解析出来的所有键
      // 文件上传选择相关
      fileDialogVisible: false,
      jsonObject: null,
      treeData: [],
      treeProps: { children: 'children', label: 'key' },
      selectedKey: null,
      selectedValue: null
    }
  },
  watch: {
    // 监听 JSON 输入变化，重新解析
    'form.jsonData': function(val) {
      this.extractJsonKeys(val)
    }
  },
  created() {
    this.generateLevelOptions()
  },
  methods: {
    generateLevelOptions() {
      this.levelOptions = Array.from({ length: 25 }, (_, i) => `${i + 1}k`)
    },
    /** 文件上传处理 */
    handleFile(file) {
      const reader = new FileReader()
      reader.onload = e => {
        try {
          const json = JSON.parse(e.target.result)
          this.jsonObject = json
          this.treeData = this.buildTree(json)
          this.fileDialogVisible = true
        } catch (err) {
          this.$message.error('JSON 文件解析失败')
        }
      }
      reader.readAsText(file)
      return false
    },
    /** 构建树形数据 */
    buildTree(obj, path = '') {
      if (typeof obj !== 'object' || obj === null) return []
      return Object.keys(obj).map(key => {
        const fullPath = path ? `${path}.${key}` : key
        const val = obj[key]
        return {
          key: fullPath,
          children: typeof val === 'object' && val !== null ? this.buildTree(val, fullPath) : null
        }
      })
    },
    extractJsonKeys(jsonStr) {
      try {
        const obj = JSON.parse(jsonStr)
        const topKeys = []
        const itemKeys = new Set()

        if (typeof obj === 'object' && obj !== null) {
          if (!Array.isArray(obj)) {
            // 顶层是对象，先收集顶层键
            topKeys.push(...Object.keys(obj))

            // 找到值是数组且数组第一项是对象，提取字段
            for (const key of topKeys) {
              const val = obj[key]
              if (Array.isArray(val) && val.length > 0 && typeof val[0] === 'object' && val[0] !== null) {
                Object.keys(val[0]).forEach(k => itemKeys.add(k))
              }
            }
          } else {
            // 顶层直接是数组
            if (obj.length > 0 && typeof obj[0] === 'object' && obj[0] !== null) {
              Object.keys(obj[0]).forEach(k => itemKeys.add(k))
            }
          }
        }

        // 可选字段：顶层键 + 子项对象字段，去重
        this.jsonKeys = Array.from(new Set([...topKeys, ...itemKeys]))
      } catch (e) {
        this.jsonKeys = []
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$message.success('提交成功，系统正在解析！')
          analyzeWordFromJson(this.form).then((data) => {
            this.$message.success('解析成功！')
            this.$emit('transfer', data)
            this.$emit('update:visible', false)
          }).catch(() => {
            this.$message.error('解析失败！')
          })
        } else {
          this.$message.error('请填写必填项！')
          return false
        }
      })
    },
    /** 左侧树点击 */
    selectKey(node) {
      this.selectedKey = node.key
      const keys = node.key.split('.')
      let val = this.jsonObject
      keys.forEach(k => (val = val[k]))
      this.selectedValue = val
    },

    /** 确认选择键 */
    confirmKey() {
      if (!this.selectedKey) {
        this.$message.warning('请先选择一个键')
        return
      }
      // 自动填充到表单 listKey
      this.form.listKey = this.selectedKey
      // 同时填充 JSON 文本框为整个 JSON
      this.form.jsonData = JSON.stringify(this.selectedValue, null, 2)
      this.fileDialogVisible = false
      // 触发解析 jsonKeys 更新下拉选项
      this.extractJsonKeys(this.form.jsonData)
    }
  }
}
</script>
<style scoped>
.json-upload-input {
  display: flex;

  .el-upload-dragger {
    height: 140px !important;
  }
}
</style>
